package com.geeke.sys.service;

import java.util.List;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.StringUtils;

import com.geeke.common.service.TreeService;
import com.geeke.common.data.PageRequest;
import com.geeke.common.data.Parameter;
import com.geeke.config.exception.CommonJsonException;

import com.geeke.sys.dao.RouterDao;
import com.geeke.sys.entity.Router;
import com.geeke.utils.ResultUtil;
import com.geeke.utils.constants.ErrorEnum;
import com.google.common.collect.Lists;

/**
 * 路由表 Service
 */
@Service("routerService")
@Transactional(readOnly = true)
public class RouterService extends TreeService<RouterDao, Router> {

    @Override
    public Router get(String id) {
        return super.get(id);
    }

    @Transactional(readOnly = false)
    @Override
    public Router save(Router router) {
        // 重复性检查
        List<Parameter> params = Lists.newArrayList();
        
        // 名称重复性检查
        params.clear();
        params.add(new Parameter("router.name", "=", router.getName()));
        params.add(new Parameter("router.parent_id", "=", router.getParent().getId()));
        params.add(new Parameter("router.del_flag", "=", router.getDelFlag()));

        if(!StringUtils.isBlank(router.getId())) {
          params.add(new Parameter("router.id", "<>", router.getId()));
        }

        if(this.dao.count(new PageRequest(params)) > 0) {
            throw new CommonJsonException(ResultUtil.warningJson(ErrorEnum.E_50001, "已存在相同名称"));
        }
        
        // 编号重复性检查
        if (!StringUtils.isBlank(router.getCode())) {
            params.clear();
            params.add(new Parameter("router.code", "=", router.getCode()));
            params.add(new Parameter("router.del_flag", "=", router.getDelFlag()));
            
            if(!StringUtils.isBlank(router.getId())) {
              params.add(new Parameter("router.id", "<>", router.getId()));
            }
            
            if(this.dao.count(new PageRequest(params)) > 0) {
                throw new CommonJsonException(ResultUtil.warningJson(ErrorEnum.E_50001, "已存在相同编号"));
            }
        }

        return super.save(router);
    }

    @Override
    @Transactional(readOnly = false)
    public int delete(Router router) {
        return super.delete(router);
    }
} 